package com.mars.component.scheduler.spring;

import java.lang.reflect.Method;
import java.util.Map;

import org.springframework.util.ReflectionUtils;

import com.mars.component.scheduler.exception.SchedulerJobException;

public class ScheduleRunnable implements Runnable {
	
	private Object target;
	private Method method;
	private Map<String, Object> params;

	public ScheduleRunnable(String beanName, String methodName, Map<String, Object> params) throws NoSuchMethodException, SecurityException {
		try {
			this.target = null; //SpringContextHolder.getBean(beanName);
			this.params = params;
			
			if(null != params && !params.isEmpty()){
				this.method = target.getClass().getDeclaredMethod(methodName, String.class);
			}else{
				this.method = target.getClass().getDeclaredMethod(methodName);
			}
		} catch (Exception e) {
			throw new SchedulerJobException("运行的Bean实例不存在，BeanName：%s", beanName) ;
		}
	}
	
	@Override
	public void run() {
		try {
			ReflectionUtils.makeAccessible(method);
			if(null != params && !params.isEmpty()){
				method.invoke(target, params);
			}else{
				method.invoke(target);
			}
		}catch (Exception e) {
			throw SchedulerJobException.RUN_SCHEDULER_FAILED.logError(e) ;
		}
	}

}
